package com.tancw.cloud.auth.service.impl;

import com.tancw.cloud.auth.service.AuthService;
import com.tancw.cloud.common.Result;
import com.tancw.cloud.common.util.JwtUtil;
import com.tancw.cloud.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 认证服务实现
 */
@Slf4j
@DubboService
@Service
public class AuthServiceImpl implements AuthService {
    
    @DubboReference
    private UserService userService;

    @Override
    public Result<Map<String, String>> login(String username, String password) {
        log.info("用户登录: {}", username);

        // 简化演示，实际应该调用用户服务验证
        if ("admin".equals(username) && "123456".equals(password)) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId", 1L);
            claims.put("username", username);

            String token = JwtUtil.generateToken(claims);

            Map<String, String> result = new HashMap<>();
            result.put("token", token);
            result.put("username", username);

            return Result.success(result);
        }

        return Result.fail("用户名或密码错误");
    }

    @Override
    public Result<String> register(String username, String password) {
        log.info("用户注册: {}", username);
        
        // 实际应该调用用户服务注册
        return Result.success("注册成功");
    }

    @Override
    public Result<Map<String, Object>> validate(String token) {
        try {
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }

            if (JwtUtil.isTokenExpired(token)) {
                return Result.fail("Token已过期");
            }

            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("userId", JwtUtil.getUserId(token));
            userInfo.put("username", JwtUtil.getUsername(token));

            return Result.success(userInfo);
        } catch (Exception e) {
            return Result.fail("Token无效");
        }
    }
}